package main

import (
	"context"
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/zrpc"
	"go-zero-demo/user-rpc/internal/config"
	"go-zero-demo/user-rpc/internal/initialize/nacos"
	"go-zero-demo/user-rpc/internal/initialize/viper"
	"go-zero-demo/user-rpc/internal/server"
	"go-zero-demo/user-rpc/internal/svc"
	"go-zero-demo/user-rpc/pb"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"time"
)

var configFile = flag.String("f", "user-rpc/etc/user.yaml", "the config file")

// 调试工具 go install github.com/fullstorydev/grpcui/cmd/grpcui@latest
// https://github.com/fullstorydev/grpcui grpc 调试工具
func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	ctx := svc.NewServiceContext(c)
	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		pb.RegisterUserCenterServer(grpcServer, server.NewUserCenterServer(ctx))
		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})
	defer s.Stop()
	interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		st := time.Now()
		resp, err = handler(ctx, req)
		logx.Info("method: %s time: %v\n", info.FullMethod, time.Since(st))
		return resp, err
	}
	s.AddUnaryInterceptors(interceptor)
	// register nacos
	nacos.RegisterNacos(c)
	// client config
	viper.InitViperConfig()

	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}
